package com.gmail.at.controller;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.gmail.at.model.Passenger;
import com.gmail.at.service.PassengerService;
import com.gmail.at.utils.Message;

@RequestMapping("/registration")
@Controller
public class RegistrationController {

	final Logger logger = LoggerFactory.getLogger(RegistrationController.class);

	@Autowired
	private PassengerService passengerService;

	@Autowired
	MessageSource messageSource;

	@RequestMapping(method = RequestMethod.GET)
	public String showRegistration(Model uiModel) {
		Passenger passenger = new Passenger();
		uiModel.addAttribute("passenger", passenger);
		return "main/registration";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processRegistration(@Valid Passenger passenger,
			BindingResult bindingResult, Model uiModel,
			HttpServletRequest httpServletRequest,
			RedirectAttributes redirectAttributes, Locale locale) {
		logger.info("Registering passengers");
		if (bindingResult.hasErrors()) {
			uiModel.addAttribute(
					"message",
					new Message("error", messageSource.getMessage(
							"passenger_registration_fail", new Object[] {},
							locale)));
			uiModel.addAttribute("passenger", passenger);
			return "main/registration";
		}
		String result = passengerService.registration(passenger);
		if (result.equals("ok")) {
			uiModel.asMap().clear();
			redirectAttributes.addFlashAttribute(
					"message",
					new Message("success", messageSource.getMessage(
							"passenger_registration_success", new Object[] {},
							locale)));
			passengerService.registration(passenger);
			return "redirect:/";
		} else {
			uiModel.addAttribute("message", new Message("error", result));
			uiModel.addAttribute("passenger", passenger);
			return "main/registration";
		}
	}
}
